<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>

      <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="doSearch">查询</el-button>

    </div>

    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')">添加企业</el-button>

    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="EnterpriseList" @expand-change="expandChange">
        <!-- 要折叠的内容区域 -->
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.rentData">
              <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="scope">
                  <el-tag :type="tabcolor(scope.row.status)">{{ tab(scope.row.status) }}</el-tag>
                </template>

              </el-table-column>
              <el-table-column label="操作" width="180">
                <!-- #default="scope" -->
                <template #default="scope">
                  <el-button size="mini" type="text" :disabled="scope.row.status===3" @click="outRent(scope.row.id)">退租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status===3" @click="adddRent(scope.row)">续租</el-button>
                  <el-button size="mini" type="text" :disabled="scope.row.status!==3" @click="deleteRent(scope.row.id)">删除</el-button>

                </template>

              </el-table-column>

            </el-table>

          </template>

        </el-table-column>
        <el-table-column type="index" label="序号" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column
          label="联系电话"
          prop="contactNumber"
        />
        <el-table-column label="操作">
          <!-- #default="scope" -->
          <template #default="scope">
            <el-button size="mini" type="text" @click="addRent(scope.row.id)">添加合同</el-button>

            <el-button size="mini" type="text" @click="look(scope.row.id)">查看</el-button>

            <el-button size="mini" type="text" @click="edit(scope.row.id)">编辑</el-button>

            <el-button size="mini" type="text" :disabled="scope.row.existContractFlag===1" @click="deletee(scope.row.id)">删除</el-button>

          </template>

        </el-table-column>

      </el-table>

    </div>

    <div class="page-container">
      <el-pagination
        layout="total,sizes, prev, pager, next"
        :page-size="params.pageSize"
        :total="total"
        :page-sizes="[2, 5, 10]"
        @current-change="pageChange"
        @size-change="handleSizeChange"
      />
    </div>
    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @click="closeDialog"
    >
      <!-- 表单区域 :rules="rentRules" -->
      <div class="form-container">
        <el-form ref="addForm" :model="rentForm" :rules="rentRules" label-position="top">
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in buildlist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

          </el-form-item>

          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="租赁合同" prop="contractId">
            <el-upload
              :before-upload="beforeupload"
              action="#"
              :http-request="uploadRequest"
              :limit="1"
              :on-exceed="exceed"
              :file-list="fileList"
            >
              <el-button size="small" type="primary" plain>上传合同文件</el-button>

              <div slot="tip" class="el-upload__tip">支持扩展名：.doc .docx .pdf, 文件大小不超过5M</div>

            </el-upload>

          </el-form-item>

        </el-form>

      </div>

      <template #footer>
        <el-button size="mini" @click="closeDialog">取 消</el-button>

        <el-button size="mini" type="primary" @click="creatrent()">确 定</el-button>

      </template>

    </el-dialog>

  </div>

</template>
<script>
import { getRentBuildListAPI } from '@/api/building'
import { getEnterpriseListAPI, uploadAPI, deleteEnterpriseAPI, addRentAPI, getRentlistAPI, outRentAPI, deleteRentAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      params: {
        name: '',
        page: 1,
        pageSize: 5
      },
      total: 0,
      EnterpriseList: [],
      rentDialogVisible: false,
      rentForm: {
        buildingId: 0, // 租赁楼宇id
        // startTime: '',
        // endTime: '',
        rentTime: [], // 合同时间
        contractId: 0, // 合同id
        contractUrl: '', // 合同Url
        type: 0,
        enterpriseId: 0
      },
      buildlist: [],
      fileList: [],
      rentRules: {
        buildingId: [{
          required: true, message: '请选择楼宇', trigger: 'change'
        }],
        rentTime: [{
          required: true, message: '请选择租赁日期', trigger: 'change'
        }],
        contractId: [{
          required: true, message: '请上传租赁合同'
        }]
      }

    }
  },
  async created() {
    this.getEnterpriseList()
    // 渲染楼宇下拉列表
    // 获取楼宇下拉列表
    const res = await getRentBuildListAPI()
    console.log(res)
    this.buildlist = res.data
  },
  methods: {
    // 数据渲染
    async getEnterpriseList() {
      const res = await getEnterpriseListAPI(this.params)
      this.EnterpriseList = res.data.rows
      this.total = res.data.total
      console.log(res)
      const newData = res.data.rows.map(item => {
        return {
          ...item,
          rentData: []
        }
      })
      this.EnterpriseList = newData
      // console.log(newData)
    },
    // 分页器的实现
    pageChange(page) {
      //  把点击的页数赋值给请求参数页数
      this.params.page = page
      // 使用最新请求获取列表数据
      this.getEnterpriseList()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      //  把点击的页数赋值给请求参数页数
      this.params.pageSize = val
      // 使用最新请求获取列表数据
      this.getEnterpriseList()
    },
    // 搜索功能的实现
    doSearch() {
    //  搜索是需要跳转第一页，根据条件进行查询
    // 调用接口前吧页数参数重置为1
      this.params.page = 1
      this.getEnterpriseList()
    },
    // 编辑
    edit(id) {
      // console.log(id)
      this.$router.push({
        path: '/exterpriseAdd',
        query: {
          id
        }
      })
    },
    // 删除
    // 删除单个数据
    deletee(id) {
      this.$confirm('此操作将永久删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        console.log(2)
        const res = await deleteEnterpriseAPI(id)
        this.doSearch()
        if (res.code === 10000) {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          return this.$message.error('删除失败' + res.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加合同(打开)  少个校验
    addRent(id) {
      // 记录当前添加合同的企业id
      this.rentForm.enterpriseId = id
      this.rentDialogVisible = true
    },
    // （关闭）
    closeDialog() {
      this.rentDialogVisible = false
    },
    // 限制上传合同的提示信息
    exceed(files, fileList) {
      this.$message.warning('文件超出个数限制')
    },
    beforeupload(file) {
      console.log(file)

      // 规定文件后缀名
      // const accessTypeList = ['image/png', 'image/jpg', 'image/jpeg']
      //   规定文件大小
      const maxSize = 2 * 1024 * 1024
      //   类型校验是否通过
      const typeFlag = ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'].includes(file.type)
      //   文件类型校验是否通过
      if (!typeFlag) {
        this.$message.error('只能上传png、jpg、jpeg文件')
        return typeFlag
      }
      //   文件大小校验是否通过  fileflag &&
      const sizeflag = file.size <= maxSize
      if (!sizeflag) {
        this.$message.error('文件不能超过5MB')
        return sizeflag
      }
      return typeFlag && sizeflag
    },
    // 上传合同
    async uploadRequest(data) {
      const formData = new FormData()
      // 往数组或者对象里面添加元素
      // 添加文件
      formData.append('file', data.file)
      // 文件类型
      formData.append('type', 'contract')
      // 调用接口
      const res = await uploadAPI(formData)
      console.log(res)
      if (res.code === 10000) {
        this.rentForm.contractId = res.data.id
        this.rentForm.contractUrl = res.data.url
      }
    },
    // 给企业创建合同
    async creatrent() {
      const form = {
        ...this.rentForm
      }
      form.startTime = form.rentTime[0]
      form.endTime = form.rentTime[1]
      console.log(form)
      delete form.rentTime
      const res = await addRentAPI(form)
      console.log(res)
      if (res.code === 10000) {
        this.$message.success('新增成功')
      } else {
        this.$message.error('新增失败' + res.msg)
      }
      this.rentDialogVisible = false
    },
    // 查看合同
    async look(id) {
      this.$router.push({
        path: '/exterpriseDetail',
        query: {
          id
        }
      })
      this.rentDialogVisible = true
      // 获取楼宇下拉列表
      // const res = await addRentAPI()
      // this.buildList = res.data
    },
    // 展开数据
    async expandChange(row, rows) {
      // 展示的当前行的数据
      console.log(row)
      // 获取当前企业对应的合同
      const res = await getRentlistAPI(row.id)
      // console.log(res)
      // 堵住eslint的嘴 是 ESLint 中的一个注释指令，用于禁用特定规则对下一行代码的检查。下面我们来详细解释这个注释以及它涉及的规则。
      // eslint-disable-next-line require-atomic-updates
      row.rentData = res.data
    },
    // 状态的格式化
    tab(status) {
      const MAP = {
        0: '待生效',
        1: '生效中',
        2: '已到期',
        3: '已退租'
      }
      return MAP[status]
    },
    tabcolor(status) {
      const Mapcolor = {
        0: 'warning',
        1: 'success',
        2: 'info',
        3: 'danger'
      }
      return Mapcolor[status]
    },
    // 退租
    outRent(rentId) {
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 1. 调用接口
        const res = await outRentAPI(rentId)
        if (res.code === 10000) {
          // 2. 重新拉取列表
          this.getEnterpriseList()
          this.$message({
            type: 'success',
            message: '退租成功!'
          })
        } else {
          this.$message({
            type: 'info',
            message: '退租失败'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除企业的租赁合同
    async deleteRent(rentId) {
      // 二次确认
      this.$confirm('确认退租吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 1. 调用接口
        const res = await deleteRentAPI(rentId)
        if (res.code === 10000) {
          // 2. 重新拉取列表
          this.getEnterpriseList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          this.$message({
            type: 'info',
            message: '删除失败'
          })
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 续租
    adddRent(row) {
      console.log(row)
      this.rentForm.buildingId = row.buildingId
      this.rentForm.buildingName = row.buildingName
      this.rentForm.rentTime[0] = row.startTime
      this.rentForm.rentTime[1] = row.endTime
      this.rentDialogVisible = true
    }

  }
}
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
